TestRunner = function() {
  
};

TestRunner.prototype.runTests = function() {
  var testsToRun = new Array;
  for(var prop in window) {
    if (prop.indexOf('test') == 0 && typeof(window[prop]) == 'function') {
      testsToRun.push(window[prop]);
    }
  }
  this._setUpDebugPanel();
  var allSuccesful = true;
  var passedTests = 0;
  for(var i = 0; i < testsToRun.length; i++) {
    var testFn = testsToRun[i];
    var testReport = {
      testName: testFn.name
    };
    try {
      testFn.call();
      passedTests++;
    } catch (e) {
      allSuccesful = false;
      testReport.error = e;
    }
    this._writeTestReport(testReport);
  }
  if (allSuccesful) {
    this._writeSuccess('All test passed!!');
  } else {
    this._writeInfo(passedTests + ' succesful test(s) out of ' + testsToRun.length);
  }
};

TestRunner.prototype._setUpDebugPanel = function() {
  this.debugPanel = document.createElement('div');
  this.debugPanel.setAttribute('id', 'debugPanel');
  document.body.appendChild(this.debugPanel);
};

TestRunner.prototype._writeTestReport = function(testReport) {
  var message = '<p><span style="color: blue">Running test: ' + testReport.testName  + '</span><br/>';
  if (testReport.error == undefined) {
    message += ('<span style="color: green"> Succes</span>');
  } else {
    if (testReport.error instanceof JsUnitException) {
      message += ('<span style="color: red"> Failure: ' + testReport.error.comment + ' : ' + testReport.error.jsUnitMessage + '</span>');
      if (testReport.error.stackTrace) {
        message += '</br>';

        var stackTrace = testReport.error.stackTrace.split('> ');
        for(var i = 0; i < stackTrace.length; i++) {
          message += '<span> &gt; ' + stackTrace[i] + '</span><br/>';
        }
      }
    } else {
      message += ('<span style="color: red"> Failure: ' + testReport.error.description + '</span>');
      if (testReport.error.stackTrace) {
        message += '</br>';

        var stackTrace = testReport.error.stackTrace.split('> ');
        for(var i = 0; i < stackTrace.length; i++) {
          message += '<span> &gt; ' + stackTrace[i] + '</span><br/>';
        }
      }
    }
  }
  message += '</p>';
  this.debugPanel.innerHTML += message;
};

TestRunner.prototype._writeInfo = function(infoMessage) {
  this.debugPanel.innerHTML += ('<p><span>' + infoMessage + '</span></p>');
};

TestRunner.prototype._writeSuccess = function(successMessage) {
  this.debugPanel.innerHTML += ('<p><span style="color: green;">' + successMessage + '</span></p>');
};